﻿namespace DomainSerializer.Controllers
{
    using DomainSerializer.Domains;
    using System;
    using System.Runtime.Serialization;
    using System.Xml;
    using System.Linq;

    class DomainXMLReader
    {
        /// <summary>
        /// Deserializes the specified xml file.
        /// </summary>
        /// <param name="filename">Filename.</param>
        /// <param name="recipient">The recipient for deserialize.</param>
        /// <returns>object or array of object or null</returns>
        public object Deserialize(string filename, Type type)
        {
            //Type type = recipient.GetType();
            var ds = new DataContractSerializer(type);
            var settingsForReader = new XmlReaderSettings { };

            if (type.IsArray)
            {
                var temp = Array.CreateInstance(type, 1);

                using (var r = XmlReader.Create(filename, settingsForReader))
                    temp = ds.ReadObject(r) as Array;

                return temp;
            }
            else if (type.GetInterfaces().Select(elem => elem).Contains(typeof(IDomain)))
            {
                var temp = Activator.CreateInstance(type);

                using (var r = XmlReader.Create(filename, settingsForReader))
                    temp = ds.ReadObject(r);

                return temp;
            }

            return null;
        }
    }
}
